from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user
from inc.models import AdminUser, OperationLog, db, WechatConfig
from admin.admin.admin_class import LoginForm
from datetime import datetime

admin_auth_bp = Blueprint('admin_auth', __name__)

@admin_auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    """简化登录逻辑，仅保留基本认证"""
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        user = AdminUser.query.filter_by(username=username).first()
        if user and user.verify_password(password):
            login_user(user)
            return redirect(url_for('admin.dashboard'))
        else:
            flash('用户名或密码错误', 'danger')
    form = LoginForm()
    if form.validate_on_submit():
        user = AdminUser.query.filter_by(username=form.username.data).first()
        if user:
            # 检查账号是否被锁定
            if user.login_attempts >= 5:
                flash('您的账号因多次登录失败已被锁定，请联系管理员', 'danger')
                return render_template('login.html', form=form)

            # 检查密码是否过期（90天）
            if (datetime.now() - user.password_changed_at).days > 90:
                flash('您的密码已过期，请修改密码', 'danger')
                login_user(user)
                return redirect(url_for('admin.dashboard'))

            if user.verify_password(form.password.data):
                if not user.is_active:
                    flash('您的账号已被禁用，请联系管理员', 'danger')
                    return render_template('login.html', form=form)

                # 重置登录尝试次数
                user.login_attempts = 0
                login_user(user, remember=form.remember_me.data)
                user.last_login = db.func.now()
                db.session.commit()

                OperationLog.create(
                    admin_id=user.id,
                    action="登录系统",
                    resource="Auth",
                    details=f"用户 {user.username} 登录系统",
                    success=True,
                    ip_address=request.remote_addr
                )

                next_page = request.args.get('next')
                if not next_page or not next_page.startswith('/'):
                    next_page = url_for('admin.dashboard')
                flash('登录成功！', 'success')
                return redirect(next_page)
            else:
                # 增加登录尝试次数
                user.login_attempts = AdminUser.login_attempts + 1
                db.session.commit()

                OperationLog.create(
                    admin_id=None,
                    action="登录尝试",
                    resource="Auth",
                    details=f"失败的登录尝试，用户名: {form.username.data}",
                    success=False,
                    ip_address=request.remote_addr
                )

                if user.login_attempts >= 3:
                    flash(f'用户名或密码错误！剩余尝试次数: {5 - user.login_attempts}', 'danger')
                else:
                    flash('用户名或密码错误！', 'danger')
        else:
            OperationLog.create(
                admin_id=None,
                action="登录尝试",
                resource="Auth",
                details=f"失败的登录尝试，用户名: {form.username.data}",
                success=False,
                ip_address=request.remote_addr
            )
            flash('用户名或密码错误！', 'danger')
    config = WechatConfig.query.first()
    wechat_login_enabled = config and config.login_enabled if config else False
    return render_template('admin/login.html', form=form, wechat_login_enabled=wechat_login_enabled)

@admin_auth_bp.route('/logout')
def logout():
    """简化登出逻辑"""
    logout_user()
    flash('您已成功退出登录。', 'info')
    return redirect(url_for('admin.admin_auth.login'))